<?php

function EJAddCalendarEvent(&$calendarParams) {
    $aid = "aidAddCalendarEvent";
    return EJExecuteWithAuthenticatedFamily($aid, $calendarParams, function ($fid, $aid, &$calendarParams) {
        if (EJInsertCalendarEvent($calendarParams, $fid)) {
            return W3CreateSuccessfulResult();
        }

        return W3CreateFailedResult();
    });
}

function EJIsCalendarEventHappenThisMonth($currentYear, $currentMonth, $eventDatetime, $repeat) {
    $time = explode("-", $eventDatetime);
    $eventYear = intval($time[0]);
    $eventMonth = intval($time[1]);

    if ($repeat <= 0) {
        return ($currentYear == $eventYear) && ($currentMonth == $eventMonth);
    }

    $eventTotalMonth = $eventYear * 12 + $eventMonth;
    $currentTotalMonth = $currentYear * 12 + $currentMonth;
    return (($currentTotalMonth - $eventTotalMonth) % $repeat) == 0;
}

function EJGetCalendarEvent(&$calendarParams) {
    $aid = "aidCalendarEvent";
    return EJExecuteWithAuthenticatedFamily($aid, $calendarParams, function ($fid, $aid, &$calendarParams) {
        $paramOffset = 1; # The first one is the whole string from reg match
        $monthStr = $calendarParams[W3GetAPIParamIndex($aid, "month") + $paramOffset];

        $time = explode("-", $monthStr);
        $currentYear = intval($time[0]);
        $currentMonth = intval($time[1]);
        $nextMonth = $currentMonth + 1;
        $nextYear = $currentYear;
        if ($nextMonth == 13) {
            $nextMonth = 1;
            $nextYear = $currentYear + 1;
        }

        $sql = "select " .
             "calendar.Datetime as datetime, calendar.Name as name, calendar.Note as note, calendar.RepeatMonth as repeatmonth" .
             " from " .
             "calendar" .
             " where " .
             "calendar.Datetime < " . W3MakeDateSingleQuotString($nextYear, $nextMonth, 1) .
             " and " .
             "calendar.FID=" . $fid .
             " order by calendar.Datetime asc";
        $result = "{" . W3CreateSuccessfulPartialResult() . "," . W3MakeString(w3ApiResultData) . ":[";
        EJReadTable($sql, function ($row) use (&$result, $currentYear, $currentMonth, $aid) {
            $apiDef = W3GetAPIDef($aid);
            $columns = $apiDef[w3ApiResult][w3ApiResultData];

            if (!EJIsCalendarEventHappenThisMonth($currentYear, $currentMonth, $row["datetime"], $row["repeatmonth"])) {
                return;
            }
        
            $result .= "{";
            foreach ($columns as $value) {
                $resultForColumn = $row[$value[w3ApiDataValue]];
                $result .= W3MakeString($value[w3ApiDataValue]) . ":" . W3MakeString($resultForColumn) . ",";
            }
            $result = rtrim($result, ",") . "},";
        });
        $result = rtrim($result, ",") . "]}";

        return $result;
    });
}

function EJInsertCalendarEvent(&$eventParams, $fid) {
    if (!EJConnectDB()) {
        W3LogWarning("No DB connection when insert calendar event");
        return false;
    }

    $columns = array ("Name", "Datetime", "RepeatMonth", "Note", "FID");
    $size = sizeof($columns);

    $uselessParamCount = 2; # Match string, session, etc.
    $paramOffset = 1; # 0 is for the whole match string in reg
    if (sizeof($eventParams) - $uselessParamCount != $size - 1) { # 1 for FID
        W3LogWarning("No enough fields for calendar event insert: require " .
                   strval($size - 1) . # 1 for FID
                   " but actual is " .
                   strval(sizeof($eventParams) - $paramOffset));
        return false;
    }

    $aid = "aidAddCalendarEvent";

    $eventName = EJDecodeURLString($eventParams[W3GetAPIParamIndex($aid, "name") + $paramOffset]);
    $eventNote = EJDecodeURLString($eventParams[W3GetAPIParamIndex($aid, "note") + $paramOffset]);
    $values = array(W3MakeSingleQuotString($eventName),
                    W3MakeSingleQuotString($eventParams[W3GetAPIParamIndex($aid, "datetime") + $paramOffset]),
                    $eventParams[W3GetAPIParamIndex($aid, "repeatmonth") + $paramOffset],
                    W3MakeSingleQuotString($eventNote),
                    $fid);
    $sql = "insert into calendar (" . implode(",", $columns) . ") values (" . implode("," , $values) . ")";
    if (!EJExecuteSQL($sql)) {
        W3LogWarning("Execute calendar event insert SQL failed");
        return false;
    }

    return true;
}

?>
